import preferences from '@ohos.data.preferences'
/**
 * 首选项的工具实现
 */
class PrefenceUtils{
  tag ='PrefenceUtils'
  prefMap:Map<string,preferences.Preferences> = new Map()
  async loadPrefence(context,name:string){
    try {
      let pref = await preferences.getPreferences(context, name)
      this.prefMap.set(name, pref)
      console.log(this.tag, '加载preference[' + name + '] 成功')
    } catch (error) {
      console.log(this.tag,'加载preference['+name+'] 失败'+JSON.stringify(error))
    }
  }

  async put(name:string,key:string,value:preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log(this.tag,name+'未初始化')
      return
    }
    let pref = this.prefMap.get(name)
    await pref.put(key,value)
    await pref.flush()
  }

  async get(name:string,key:string,defaultV:preferences.ValueType):Promise<preferences.ValueType>{
    if(!this.prefMap.has(name)){
      console.log(this.tag,name+'未初始化')
      return
    }
    let pref = this.prefMap.get(name)
    let res = await pref.get(key,defaultV)
    return res
  }

}

const prefenceUtil = new PrefenceUtils()
export default prefenceUtil as PrefenceUtils